﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections.Concurrent;
using SharpShare.Storage.Filter;

namespace SharpShare.Storage.Zip {
    public class ZipArchiveBrowseFilter : StorageFilter {
        private ConcurrentDictionary<IStorageFile, ZipArchiveStorageItem> _archives = new ConcurrentDictionary<IStorageFile, ZipArchiveStorageItem>();

        public ZipArchiveBrowseFilter() {

        }

        public string ProviderName { get; set; }

        private ZipArchiveStorageItem OpenArchive(IStorageFile file) {
            if (!_archives.ContainsKey(file)) {
                IStorageDataProvider dataProvider = null;
                bool fileAvailable = false;

                try {
                    if (file.Length > 0) {
                        dataProvider = file.Open(StorageFileAccess.Read, StorageFileAccess.None);
                        fileAvailable = true;
                    }
                } catch {

                } finally {
                    if (dataProvider != null) {
                        dataProvider.Close();
                    }
                }

                if (!fileAvailable) {
                    return null;
                }
            }

            ZipArchiveStorageItem item = _archives.GetOrAdd(file, f => new ZipArchiveStorageItem(f, true));

            return item;
        }

        public override IStorageLookup ModifyContents(FilterScope<IStorageContainer> container, IStorageLookup contents) {
            return contents.Attach(item => {
                IStorageFile file = item.AsFile();

                if (file == null) {
                    return new IStorageItem[] { };
                }

                if (item.Name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) {
                    ZipArchiveStorageItem archive = OpenArchive(file);
                    if (archive != null) {
                        return new IStorageItem[] { archive };
                    }
                }

                return new IStorageItem[] { };
            });
        }
    }
}
